package cn.cherish.one2many;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.common.protocol.heartbeat.MessageModel;

import java.util.List;

public class Comsumer {
    public static void main(String[] args) throws MQClientException {
        // 谁来接收
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("group1");
        // 从哪里取
        consumer.setNamesrvAddr("localhost:9876");
        // 设置消费模式(默认使用集群模式)
        consumer.setMessageModel(MessageModel.BROADCASTING);
        // 监听谁
        consumer.subscribe("topic4","*");
        consumer.setConsumeTimeout(100000);
        // 注册监听器
        consumer.registerMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
                for (MessageExt messageExt : list) {
                    System.out.println(messageExt);
                    byte[] body = messageExt.getBody();
                    System.out.println(new String(body));
                }
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });
        // 启动消费者
        consumer.start();
        System.out.println("消费者启动！");
    }
}
